package org.zhangsh.aio;

import org.zhangsh.socket.HostInfo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-04-26
 */
public class AioTimerServer {

    private static class AsyncTimerHandler implements Runnable{

        private CountDownLatch countDownLatch = null;
        private AsynchronousServerSocketChannel socketChannel = null;

        public AsyncTimerHandler(AsynchronousServerSocketChannel socketChannel){
            this.socketChannel = socketChannel;
        }

        @Override
        public void run() {

            countDownLatch = new CountDownLatch(1);
            // 开始获取连接
            socketChannel.accept(this, new AsynchronousCompletionHandler());

            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    private static class AsynchronousCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncTimerHandler>{


        @Override
        public void completed(AsynchronousSocketChannel result, AsyncTimerHandler attachment) {
            attachment.socketChannel.accept(attachment, this);

            ByteBuffer data = ByteBuffer.allocate(30);
//            data.put()
//            result.read()


        }

        @Override
        public void failed(Throwable exc, AsyncTimerHandler attachment) {
            attachment.countDownLatch.countDown();
        }
    }

    public static void main(String[] args) throws IOException {



        // 还是现有一个channel
        AsynchronousServerSocketChannel asynchronousSocketChannel = AsynchronousServerSocketChannel.open();
        asynchronousSocketChannel.bind(new InetSocketAddress(HostInfo.HOST_NAME, HostInfo.HOST_PORT));
        // 有了channel之后，不需要Selector模型，直接就执行去

        // do


        //



    }

}
